import { defineStore } from 'pinia'
import { ref } from 'vue'

// 省市县数据结构
export interface LocationData {
  province: string
  city: string
  county: string
}

// 当前天气数据
export interface CurrentWeather {
  temp: number
  high: number
  low: number
  condition: string
  weatherCode: string
}

// 每小时预报数据
export interface HourlyForecast {
  time: string
  icon: string
  temp: number
}

// 每日预报数据
export interface DailyForecast {
  day: string
  icon: string
  high: number
  low: number
}

// 天气详情数据
export interface WeatherDetails {
  feelsLike: number
  uvIndex: number
  uvLevel: string
  sunrise: string
  sunset: string
  precipitation: number
  wind: number
  windDirection: string
  windDegree: number
  humidity: number
  dewPoint: number
  visibility: number
  visibilityDesc: string
  pressure: number
  pressureTrend: string
  aqi: number
  aqiLevel: string
}

// 省市县列表缓存（用于选择器等场景）
export interface RegionCache {
  provinces?: string[]
  cities?: Record<string, string[]>
  counties?: Record<string, string[]>
  lastUpdate?: number
}

export const useWeatherStore = defineStore('weather', () => {
  // 当前位置信息
  const location = ref<LocationData>({
    province: '四川',
    city: '成都',
    county: '成华区'
  })

  // 当前天气
  const currentWeather = ref<CurrentWeather>({
    temp: 18,
    high: 22,
    low: 15,
    condition: '多云',
    weatherCode: '01'
  })

  // 每小时预报
  const hourlyForecast = ref<HourlyForecast[]>([
    { time: '现在', icon: '⛅', temp: 18 },
    { time: '15:00', icon: '⛅', temp: 19 },
    { time: '16:00', icon: '☁️', temp: 20 },
    { time: '17:00', icon: '☁️', temp: 21 },
    { time: '18:00', icon: '⛅', temp: 22 },
    { time: '19:00', icon: '🌤️', temp: 20 },
    { time: '20:00', icon: '🌙', temp: 18 },
    { time: '21:00', icon: '🌙', temp: 17 },
    { time: '22:00', icon: '🌙', temp: 16 },
    { time: '23:00', icon: '🌙', temp: 16 },
    { time: '00:00', icon: '🌙', temp: 15 },
    { time: '01:00', icon: '🌙', temp: 15 }
  ])

  // 每日预报
  const dailyForecast = ref<DailyForecast[]>([
    { day: '今天', icon: '⛅', high: 22, low: 15 },
    { day: '周四', icon: '🌤️', high: 24, low: 16 },
    { day: '周五', icon: '☀️', high: 26, low: 18 },
    { day: '周六', icon: '🌦️', high: 23, low: 17 },
    { day: '周日', icon: '⛈️', high: 20, low: 14 },
    { day: '周一', icon: '🌧️', high: 19, low: 13 },
    { day: '周二', icon: '⛅', high: 21, low: 15 },
    { day: '周三', icon: '☀️', high: 25, low: 17 },
    { day: '周四', icon: '🌤️', high: 24, low: 16 },
    { day: '周五', icon: '☁️', high: 22, low: 15 }
  ])

  // 天气详情
  const weatherDetails = ref<WeatherDetails>({
    feelsLike: 18,
    uvIndex: 5,
    uvLevel: '中等',
    sunrise: '06:15',
    sunset: '18:42',
    precipitation: 0,
    wind: 12,
    windDirection: '东北风',
    windDegree: 45,
    humidity: 65,
    dewPoint: 12,
    visibility: 10,
    visibilityDesc: '非常好',
    pressure: 1013,
    pressureTrend: '稳定',
    aqi: 45,
    aqiLevel: '优秀'
  })

  // 最后更新时间
  const lastUpdateTime = ref<string>('')

  // 省市县缓存数据
  const regionCache = ref<RegionCache>({
    provinces: [],
    cities: {},
    counties: {},
    lastUpdate: 0
  })

  // 持久化存储key
  const WEATHER_STORAGE_KEY = 'vue-desktop:weather'
  const REGION_STORAGE_KEY = 'vue-desktop:region'

  // ==================== 数据更新方法 ====================

  // 更新位置信息
  function setLocation(data: Partial<LocationData>) {
    if (data.province !== undefined) location.value.province = data.province
    if (data.city !== undefined) location.value.city = data.city
    if (data.county !== undefined) location.value.county = data.county
    saveWeatherToStorage()
  }

  // 更新当前天气
  function setCurrentWeather(data: Partial<CurrentWeather>) {
    currentWeather.value = { ...currentWeather.value, ...data }
    saveWeatherToStorage()
  }

  // 更新每小时预报
  function setHourlyForecast(data: HourlyForecast[]) {
    hourlyForecast.value = data
    saveWeatherToStorage()
  }

  // 更新每日预报
  function setDailyForecast(data: DailyForecast[]) {
    dailyForecast.value = data
    saveWeatherToStorage()
  }

  // 更新天气详情
  function setWeatherDetails(data: Partial<WeatherDetails>) {
    weatherDetails.value = { ...weatherDetails.value, ...data }
    saveWeatherToStorage()
  }

  // 更新最后更新时间
  function setLastUpdateTime(time: string) {
    lastUpdateTime.value = time
    saveWeatherToStorage()
  }

  // 批量更新所有天气数据
  function updateAllWeatherData(data: {
    location?: Partial<LocationData>
    currentWeather?: Partial<CurrentWeather>
    hourlyForecast?: HourlyForecast[]
    dailyForecast?: DailyForecast[]
    weatherDetails?: Partial<WeatherDetails>
    lastUpdateTime?: string
  }) {
    if (data.location) {
      location.value = { ...location.value, ...data.location }
    }
    if (data.currentWeather) {
      currentWeather.value = { ...currentWeather.value, ...data.currentWeather }
    }
    if (data.hourlyForecast) {
      hourlyForecast.value = data.hourlyForecast
    }
    if (data.dailyForecast) {
      dailyForecast.value = data.dailyForecast
    }
    if (data.weatherDetails) {
      weatherDetails.value = { ...weatherDetails.value, ...data.weatherDetails }
    }
    if (data.lastUpdateTime) {
      lastUpdateTime.value = data.lastUpdateTime
    }
    saveWeatherToStorage()
  }

  // 更新省市县缓存
  function updateRegionCache(data: Partial<RegionCache>) {
    regionCache.value = {
      ...regionCache.value,
      ...data,
      lastUpdate: Date.now()
    }
    saveRegionToStorage()
  }

  // ==================== 持久化方法 ====================

  // 保存天气数据到本地存储
  function saveWeatherToStorage() {
    try {
      const weatherData = {
        location: location.value,
        currentWeather: currentWeather.value,
        hourlyForecast: hourlyForecast.value,
        dailyForecast: dailyForecast.value,
        weatherDetails: weatherDetails.value,
        lastUpdateTime: lastUpdateTime.value
      }
      localStorage.setItem(WEATHER_STORAGE_KEY, JSON.stringify(weatherData))
    } catch (error) {
      console.error('保存天气数据失败:', error)
    }
  }

  // 从本地存储加载天气数据
  function loadWeatherFromStorage() {
    try {
      const raw = localStorage.getItem(WEATHER_STORAGE_KEY)
      if (!raw) return false

      const parsed = JSON.parse(raw)
      
      // 恢复数据
      if (parsed.location) location.value = parsed.location
      if (parsed.currentWeather) currentWeather.value = parsed.currentWeather
      if (parsed.hourlyForecast) hourlyForecast.value = parsed.hourlyForecast
      if (parsed.dailyForecast) dailyForecast.value = parsed.dailyForecast
      if (parsed.weatherDetails) weatherDetails.value = parsed.weatherDetails
      if (parsed.lastUpdateTime) lastUpdateTime.value = parsed.lastUpdateTime

      return true
    } catch (error) {
      console.error('加载天气数据失败:', error)
      return false
    }
  }

  // 保存省市县缓存到本地存储
  function saveRegionToStorage() {
    try {
      localStorage.setItem(REGION_STORAGE_KEY, JSON.stringify(regionCache.value))
    } catch (error) {
      console.error('保存省市县数据失败:', error)
    }
  }

  // 从本地存储加载省市县缓存
  function loadRegionFromStorage() {
    try {
      const raw = localStorage.getItem(REGION_STORAGE_KEY)
      if (!raw) return false

      const parsed = JSON.parse(raw)
      regionCache.value = parsed

      return true
    } catch (error) {
      console.error('加载省市县数据失败:', error)
      return false
    }
  }

  // 清除所有天气缓存（注销时调用）
  function clearWeatherCache() {
    // 重置为默认值
    location.value = {
      province: '四川',
      city: '成都',
      county: '成华区'
    }
    
    currentWeather.value = {
      temp: 18,
      high: 22,
      low: 15,
      condition: '多云',
      weatherCode: '01'
    }

    hourlyForecast.value = [
      { time: '现在', icon: '⛅', temp: 18 },
      { time: '15:00', icon: '⛅', temp: 19 },
      { time: '16:00', icon: '☁️', temp: 20 },
      { time: '17:00', icon: '☁️', temp: 21 },
      { time: '18:00', icon: '⛅', temp: 22 },
      { time: '19:00', icon: '🌤️', temp: 20 },
      { time: '20:00', icon: '🌙', temp: 18 },
      { time: '21:00', icon: '🌙', temp: 17 },
      { time: '22:00', icon: '🌙', temp: 16 },
      { time: '23:00', icon: '🌙', temp: 16 },
      { time: '00:00', icon: '🌙', temp: 15 },
      { time: '01:00', icon: '🌙', temp: 15 }
    ]

    dailyForecast.value = [
      { day: '今天', icon: '⛅', high: 22, low: 15 },
      { day: '周四', icon: '🌤️', high: 24, low: 16 },
      { day: '周五', icon: '☀️', high: 26, low: 18 },
      { day: '周六', icon: '🌦️', high: 23, low: 17 },
      { day: '周日', icon: '⛈️', high: 20, low: 14 },
      { day: '周一', icon: '🌧️', high: 19, low: 13 },
      { day: '周二', icon: '⛅', high: 21, low: 15 },
      { day: '周三', icon: '☀️', high: 25, low: 17 },
      { day: '周四', icon: '🌤️', high: 24, low: 16 },
      { day: '周五', icon: '☁️', high: 22, low: 15 }
    ]

    weatherDetails.value = {
      feelsLike: 18,
      uvIndex: 5,
      uvLevel: '中等',
      sunrise: '06:15',
      sunset: '18:42',
      precipitation: 0,
      wind: 12,
      windDirection: '东北风',
      windDegree: 45,
      humidity: 65,
      dewPoint: 12,
      visibility: 10,
      visibilityDesc: '非常好',
      pressure: 1013,
      pressureTrend: '稳定',
      aqi: 45,
      aqiLevel: '优秀'
    }

    lastUpdateTime.value = ''

    regionCache.value = {
      provinces: [],
      cities: {},
      counties: {},
      lastUpdate: 0
    }

    // 清除本地存储
    try {
      localStorage.removeItem(WEATHER_STORAGE_KEY)
      localStorage.removeItem(REGION_STORAGE_KEY)
    } catch (error) {
      console.error('清除天气缓存失败:', error)
    }
  }

  // ==================== 初始化 ====================

  // 尝试从本地存储加载数据
  loadWeatherFromStorage()
  loadRegionFromStorage()

  return {
    // 状态
    location,
    currentWeather,
    hourlyForecast,
    dailyForecast,
    weatherDetails,
    lastUpdateTime,
    regionCache,

    // 更新方法
    setLocation,
    setCurrentWeather,
    setHourlyForecast,
    setDailyForecast,
    setWeatherDetails,
    setLastUpdateTime,
    updateAllWeatherData,
    updateRegionCache,

    // 持久化方法
    saveWeatherToStorage,
    loadWeatherFromStorage,
    saveRegionToStorage,
    loadRegionFromStorage,
    clearWeatherCache
  }
})

